#!/usr/bin/env python

import pygtk
pygtk.require("2.0")

import gtk
import learning
import os
import stemmer as stm
import utils

import SVM

p = stm.PorterStemmer()
stopwords = utils.load('stopwords.ser')
allwords = utils.load('allwords.ser')
reFeaturesMatrix = utils.load('reFeaturesMatrix.ser')
cls = utils.load('cls.ser')
matrix2 = utils.load('matrix2.ser')
categories = utils.load('categories.ser')

def getAbstract(data):
  tag = '\nAbstract    :\n'
  abstract = data[data.find(tag) + len(tag):]
  return abstract.replace('\n', ' ').replace('  ', '')


class TutorialApp(object):
  def __init__(self):
      builder = gtk.Builder()
      builder.add_from_file("GUI-SVM.xml")

      # Get the widgets
      self.window = builder.get_object("wndIFT603")
      self.txtAbstract = builder.get_object("txtAbstract")
      self.txtResults = builder.get_object("txtResults")
      
      # Connect signals
      builder.connect_signals(self)

      # Initialise the method
      self.svm = SVM.SVM(reFeaturesMatrix, cls, allwords, matrix2)
      
      self.window.show()


  def on_btnFileChooser_selection_changed(self, data=None):
    path, filename = os.path.split(data.get_filename())
    filedata = learning.readFileData(path, filename)
    
    abstract = getAbstract(filedata)
    buf = self.txtAbstract.get_buffer()
    buf.set_text(abstract)

    categoryName = learning.readCategory(filedata)
    categoryID = categories.bag[categoryName][0]
    
    realCluster = str(cls.cat2clus[categoryID])
    words = learning.readWords(stopwords, filedata, p)
    
    clusterID = str(self.svm.classify(words))
    buf = self.txtResults.get_buffer()
    if clusterID == realCluster:
        buf.set_text('Cluster trouve!\nCluster = ' + clusterID)
    else:
        buf.set_text('Maivaise reponse!\nVrai = ' + realCluster + '  Nous =' + clusterID)

    
  def on_window_destroy(self, widget, data=None):
    gtk.main_quit()


if __name__ == "__main__":
  app = TutorialApp()
  gtk.main()

# python C:\GTK+\bin\gtk-builder-convert GUI-SVM.glade GUI-SVM.xml
